const numConversion = require('./numConversion.js');

const BLEUtil = {
  isConnected: false,

  openBLEConnection(deviceId, onSuccess, onFail) {
    wx.getConnectedBluetoothDevices({
      success: (res) => {
        console.info('已连接的设备:', res.devices);
        const device = res.devices.find(d => d.deviceId === deviceId);
        if (device) {
          console.info('设备已连接，直接获取服务');
          this.isConnected = true;
          this.getBLEDeviceServices(deviceId, onSuccess, onFail);
        } else {
          this.createBLEConnection(deviceId, onSuccess, onFail);
        }
      },
      fail: onFail,
    });
  },

  createBLEConnection(deviceId, onSuccess, onFail) {
    wx.createBLEConnection({
      deviceId,
      success: () => {
        console.info('蓝牙设备连接成功');
        this.isConnected = true;
        this.getBLEDeviceServices(deviceId, onSuccess, onFail);
      },
      fail: onFail,
    });
  },

  getBLEDeviceServices(deviceId, onSuccess, onFail) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.info('设备服务:', res.services);
        if (res.services.length > 0) {
          this.getBLEDeviceCharacteristics(deviceId, res.services[0].uuid, onSuccess, onFail);
        } else {
          console.warn('设备没有服务');
          onFail && onFail('未找到服务');
        }
      },
      fail: onFail,
    });
  },

  getBLEDeviceCharacteristics(deviceId, serviceId, onSuccess, onFail) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.info('特征值:', res.characteristics);
        if (res.characteristics.length > 0) {
          this.notifyBLECharacteristicValueChange(deviceId, serviceId, res.characteristics[0].uuid, onSuccess, onFail);
        } else {
          console.warn('未找到特征值');
          onFail && onFail('未找到特征值');
        }
      },
      fail: onFail,
    });
  },

  notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, onSuccess, onFail) {
    wx.notifyBLECharacteristicValueChange({
      deviceId,
      serviceId,
      characteristicId,
      state: true,
      success: () => {
        console.info('特征值通知已启用:', characteristicId);
        this.listenBLECharacteristicValueChange(onSuccess);
      },
      fail: onFail,
    });
  },

  listenBLECharacteristicValueChange(onDataReceived) {
    wx.onBLECharacteristicValueChange((res) => {
      console.info('收到 BLE 数据:', res);
      if (!res.value) {
        console.warn('收到的数据为空');
        return;
      }
      const receivedValue = numConversion.ab2hex(res.value);
      console.info('转换后的十六进制数据:', receivedValue);
      const receivedString = numConversion.hexToString(receivedValue);
      console.info('转换后的字符串数据:', receivedString);
      onDataReceived && onDataReceived(receivedString);
    });
  }
};

module.exports = BLEUtil;
